// stores/permission.ts
import {defineStore} from 'pinia'
import router from '@/router'
import type {RouteRecordRaw} from "vue-router";
import {fetchUserMenu} from "@/api/menu";

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    // 是否已加载动态路由
    routesLoaded: false,
    // 菜单数据列表
    menuList: [] as Menu.MenuModel[],
    // 按钮权限列表
    buttonPermissions: [] as string[]
  }),

  actions: {
    /**
     * 生成动态路由
     */
    async generateRoutes() {
      const menus = await fetchUserMenu()

      // 转换为路由配置
      const routes = this.transformRoutes(menus)

      // 添加动态路由
      function addRoute(routes: RouteRecordRaw[]) {
        if (Array.isArray(routes) && routes.length != 0) {
          routes.forEach(route => {
            if (Array.isArray(route) && route.length != 0) {
              return addRoute(route);
            }
            if (route) {
              if (router.hasRoute(route.name)) {
                router.removeRoute(route.name)
              }
              if (router.hasRoute(route.path)) {
                router.removeRoute(route.path)
              }
              router.addRoute('container', route)
            }
          })
        }
      }

      addRoute(routes)

      // 存储菜单数据
      this.menuList = menus
      // 提取按钮权限
      // this.buttonPermissions = this.extractButtons(menus)

      this.routesLoaded = true
    },

    // 预加载所有视图组件（Vite专用）

    /**
     * 将菜单结构转换为路由配置
     * @param menus 菜单数据列表
     * @returns 生成的路由配置数组
     */
    transformRoutes(menus: Menu.MenuModel[]): RouteRecordRaw[] {
      const viewComponents = import.meta.glob('@/views/**/index.vue')

      // 有效性校验白名单
      const requiredFields: (keyof Menu.MenuModel)[] = ['name', 'route', 'component']

      /**
       * 验证菜单项有效性
       */
      const validateMenuItem = (menu: Menu.MenuModel): boolean => {
        // 基础类型校验
        return menu.menuType === 2;


      }

      /**
       * 解析组件路径
       */
      const resolveComponent = (componentPath: string): RouteRecordRaw['component'] => {
        // 标准化路径格式
        const normalizedPath = componentPath
          .replace(/^\/+/, '') // 移除开头斜杠
          .replace(/\/index$/i, '') // 移除index后缀

        const fullPath = `/src/views/${normalizedPath}/index.vue`

        // 检查组件是否存在
        if (!viewComponents[fullPath]) {
          console.error(`[路由加载] 组件不存在: ${fullPath}`, {
            available: Object.keys(viewComponents)
          })
          return () => import('/src/views/error/404/index.vue')
        }

        return viewComponents[fullPath]
      }

      /**
       * 递归转换单个菜单项
       */
      const transformMenuItem = (menu: Menu.MenuModel): RouteRecordRaw | null => {
        try {

          // 跳过无效菜单项
          if (!validateMenuItem(menu)) {
            if (menu.children && menu.children.length > 0) {
              return menu.children
                .map(transformMenuItem)
                .filter(Boolean) as RouteRecordRaw[]
            } else {
              return null;
            }
          }

          // 构建路由配置
          const route: RouteRecordRaw = {
            path: menu.route!.path,
            name: menu.name!,
            component: resolveComponent(menu.route.component!),
            meta: {
              title: menu.title || '未命名路由',
              requiresAuth: menu.requiresAuth !== false,
              icon: menu.icon,
              menuType: menu.menuType,
              parentId: menu.parentId,
              sort: menu.order || 0
            },
            children: []
          }

          // 递归处理子菜单（仅处理有效子项）
          if (menu.children?.length) {
            route.children = menu.children
              .map(transformMenuItem)
              .filter(Boolean) as RouteRecordRaw[]
          }

          // 清理空children属性
          if (route.children?.length === 0) {
            delete route.children
          }

          return route
        } catch (error) {
          console.error(`[路由转换失败] ${menu.name}:`, error)
          return null
        }
      }

      // 执行转换并过滤无效项
      return menus
        .map(transformMenuItem)
        .filter(Boolean) as RouteRecordRaw[]
    },
    /**
     * 提取按钮权限
     * @param menus 菜单列表
     */
    extractButtons(menus: Menu.MenuModel[]):
      string[] {
      const buttons: string[] = []
      const traverse = (list: Menu.MenuModel[]) => {
        list.forEach(menu => {
          if (menu.buttons) {
            buttons.push(...menu.buttons)
          }
          if (menu.children) {
            traverse(menu.children)
          }
        })
      }
      traverse(menus)
      return buttons
    }
  }
})
